<?php
namespace api\modules\chongchong51\controllers;

use Yii;
use yii\web\Controller;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use izyue\admin\models\Member;
use izyue\admin\models\MemberSearch;
use izyue\admin\models\DataOrder;
use izyue\admin\models\DataOrderSearch;
use izyue\admin\models\FlowValNo;
use izyue\admin\models\FlowValNoSearch;
use linslin\yii2\curl;

/**
 * Site controller
 */
class SiteController extends Controller
{
    public $secretkey = 'D16B859B25C3B38F1BFABEE1837EA520';
    public $memberid = 'M0445';
    public function init(){
        $this->enableCsrfValidation = false; //取消post csrf验证 否则无法post数据
    }

    public function actionSubmit()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $post = Yii::$app->request->post();
        $mobile = $this->GetMobileArea($post['phone_no']);
        //print_R($mobile);exit;
        if ($mobile['catName'] == "中国移动") {
            $operator = 1;
        } elseif ($mobile['catName'] == "中国联通") {
            $operator = 2;
        } elseif ($mobile['catName'] == "中国电信"){
            $operator = 3;
        }
        $goodsid = FlowValNo::find()->where(['operator' => $operator, 'province' => $mobile['province'],'val' => $post['flow_val']])->one();
        $sign = MD5(
            'Account' . $post['phone_no'] .
            'GoodsId' . $goodsid['no'] .
            'MemberId' . $this->memberid .
            'MemberOrderId' . $post['out_order_id'] .
            'Secretkey' . $this->secretkey
        );
        $url = 'http://api.51cc.38.zonghejiaofei.net/api/FlowOrder/Recharge';
        $param = array(
            'MemberId' => $this->memberid,
            'Hmac' => $sign,
            'MemberOrderId' => $post['out_order_id'],
            'GoodsId' => $goodsid['no'],
            'Account' => $post['phone_no'],
            'Data' => date('YmdHmsB',time()),
            'Version' => '0.1',
        );
        $return = $this->curl_http($url,$param);
        $return_array = json_decode($return,true);
        switch ($return_array['Result']) {
            case 'Success':
                $result['result'] = 0;//操作成功
                $result['order_id'] = $return_array['Data']['OrderId'];//操作成功
                $result['out_order_id'] = $return_array['Data']['MemberOrderId'];//操作成功
                $result['err_desc'] = '';//错误描述
                break;
            case 'SignError':
                $result['result'] = -3;//签名错误
                $result['err_desc'] = $return_array['Message'];//错误描述
                break;
            case 'ParameterError':
                $result['result'] = -1;//参数错误
                $result['err_desc'] = $return_array['Message'];//错误描述
                break;
            case 'SystemError':
                $result['result'] = -4;//系统错误
                $result['err_desc'] = $return_array['Message'];//错误描述
                break;
            case 'InsufficientBalance':
                $result['result'] = -6;//余额不足
                $result['err_desc'] = $return_array['Message'];//错误描述
                break;
            case 'GoodsLimit':
                $result['result'] = -5;//商品下架
                $result['err_desc'] = $return_array['Message'];//错误描述
                break;
            case 'OrderExist':
                $result['result'] = -5;//商户订单号已存在
                $result['err_desc'] = $return_array['Message'];//错误描述
                break;
            case 'OtherError':
                $result['result'] = -7;//其他类型错误
                $result['err_desc'] = $return_array['Message'];//错误描述
                break;
            default:
                $result['result'] = -7;//其他类型错误

                break;
        }
        return $result;
    }
    //余额查询接口
    public function actionBlance()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $sign   =   MD5(
            'MemberId' . $this->memberid .
            'Secretkey' . $this->secretkey
        );
        $url = 'http://api.51cc.38.zonghejiaofei.net/api/Member/BalanceQuery' ;
        $param = array(
            'MemberId' => $this->memberid,
            'Hmac' => $sign,
            'Data' => date('YmdHmsB',time()),
        );
        $return = $this->curl_http($url,$param);
        $return_array = json_decode($return,true);
        switch ($return_array['Result']) {
            case 'Success':
                $result['result'] = 0;//操作成功
                $result['blance'] = $return_array['Data']['Balance'];//操作成功
                break;
            case 'SignError':
                $result['result'] = -3;//签名错误
                break;
            case 'ParameterError':
                $result['result'] = -1;//参数错误
                break;
            case 'SystemError':
                $result['result'] = -4;//系统错误
                break;
            case 'InsufficientBalance':
                $result['result'] = -6;//余额不足
                break;
            case 'OtherError':
                $result['result'] = -7;//其他类型错误
                break;
            default:
                $result['result'] = -7;//其他类型错误
                break;
        }
        return $result;
          
    }
    //订单查询接口
    public function actionQuery()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $post = Yii::$app->request->post();
        $sign   =   MD5(
            'MemberId' . $this->memberid .
            'MemberOrderId' . $post['out_order_id'] .
            'Secretkey' . $this->secretkey
        );
        $url = 'http://api.51cc.38.zonghejiaofei.net/api/FlowOrder/ReChargeQuery';
        $param = array(
            'MemberId' => $this->memberid,
            'Hmac' => $sign,
            'MemberOrderId' => $post['out_order_id'],
            'Data' => date('YmdHmsB',time()),
        );
        $return = $this->curl_http($url,$param);
        $return_array = json_decode($return,true);
        switch ($return_array['Result']) {
            case 'Success':
                $result['result'] = 0;//操作成功
                $result['status'] = $return_array['Data']['OrderState'];//订单状态
                $result['phone_no'] = $return_array['Data']['Account'];//手机号码
                $result['out_order_id'] = $return_array['Data']['MemberOrderId'];//外部订单id
                $result['order_id'] = $return_array['Data']['OrderId'];//内部订单id
                $result['err_desc'] = $return_array['Message'];//内部订单id
                break;
            case 'SignError':
                $result['result'] = -3;//签名错误
                break;
            case 'ParameterError':
                $result['result'] = -1;//参数错误
                break;
            case 'SystemError':
                $result['result'] = -4;//系统错误
                break;
            case 'OrderNotFind':
                $result['result'] = -6;//订单不存在
                break;
            case 'OtherError':
                $result['result'] = -7;//其他类型错误
                break;
            default:
                $result['result'] = -7;//其他类型错误
                break;
        }
        return $result;
        //return $return_array;
    }
    /*//回调地址接口
    public function actionBack()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;  
        $param = Yii::$app->request->post();
        $this->UpdateOrderStatus($param);
        $backurl = $this->GetBackUrl($param);
        $curl_array = array(
                    'order_id' => $param['order_id'], 
                    'out_order_id' => $param['out_order_id'], 
                    'status' => $param['status'],
                    'completion_time' => $param['completion_time'],
                    'err_desc' => $param['err_desc'],
                    );
        $return = $this->curl_http($backurl,$curl_array);
        //如果没有返回则定时回调
        return $return;  
    }*/
    public function actionBack() {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $url = Yii::$app->request->hostInfo . "/api/web/chongchong51/site/query";
        $post = Yii::$app->request->post();
        $backurl = Yii::$app->request->hostInfo . "/api/web/v1/site/back";
        $res = DataOrder::find()->where(['status' => 1,'apiid' => 3])->all();
        foreach ($res as $value) {
            $param['out_order_id'] = $value['out_order_id'];
            $backurl = $this->GetBackUrl($param);
            $return = $this->curl_http($url,$param);
            $return_array = json_decode($return,true);
            if ($return_array['result'] == "0") {
                if ($return_array['status'] == "OrderSuccess") {
                    $curl_array = array(
                        'order_id' => $return_array['order_id'],
                        'out_order_id' => $param['out_order_id'],
                        'status' => 3,
                        'completion_time' => time(),
                        'err_desc' => '',
                    );
                    $return = $this->curl_http($backurl,$curl_array);
                    $param['status'] = $curl_array['status'];
                    $this->UpdateOrderStatus($param);
                    echo 'UpdataOrderSuccess';
                } elseif ($return_array['status'] == "OrderFail") {
                    $curl_array = array(
                        'order_id' => $return_array['order_id'],
                        'out_order_id' => $param['out_order_id'],
                        'status' => 4,
                        'completion_time' => time(),
                        'err_desc' => '充值失败',
                    );
                    $return = $this->curl_http($backurl,$curl_array);
                    $param['status'] = $curl_array['status'];
                    $this->UpdateOrderStatus($param);
                    echo 'UpdataOrderSuccess';
                }
                
            }
        }
    }
    public function UpdateOrderStatus($param) {
        $res = DataOrder::find()->where(['out_order_id' => $param['out_order_id']])->one();
        DataOrder::updateAll(
            array('status'=>$param['status']),
            'out_order_id=:out_order_id',
            array(':out_order_id'=>$res['out_order_id'])
            );
    }
    public function GetBackUrl($param){
        $res = DataOrder::find()->where(['out_order_id' => $param['out_order_id']])->one();
        $info = Member::findOne($res['mid']);
        return $info['back_url'];

    }
    public function curl_http($url,$param){
        $curl = new curl\Curl();
        $response = $curl->setOption(
                CURLOPT_POSTFIELDS, 
                http_build_query($param)
                )
            ->post($url);
        return $response;
    }

    public function GetMobileArea($mobile) {
        $sms = array('province'=>'', 'supplier'=>'');    //初始化变量
        //根据淘宝的数据库调用返回值
        $url = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=".$mobile."&t=".time();
        $num = 0;
        do {
            $content = file_get_contents($url);
            $html = iconv("gb2312", "utf-8//IGNORE",$content);
            $data = explode(',', $html);
            @$province = explode(':', $data[1]);
            @$catname = explode(':', $data[2]);
            @$array = array(
                trim($province[0]) => str_replace("'","",$province[1]),
                trim($catname[0]) => str_replace("'","",$catname[1])
            );
            $num++;
        } while (empty($array['catName']) && $num < 10);
        return @$array;

    }


}
